package com.app.micaihu.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.app.micaihu.R;
import com.app.micaihu.ad.AdConfig;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.dialog.DismisiDialog;
import com.app.micaihu.custom.view.web.CustomWebView;
import com.app.micaihu.listener.AutoHeightControllerListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.okhttplib.util.AppUtils;
import com.app.utils.NetUtils;
import com.app.utils.util.AppTools;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.file.AppFileUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.baidu.mobstat.StatService;
import com.facebook.imagepipeline.image.ImageInfo;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class MutileThreadDownload {

    public static List<DownloadThread> downloadThreads;

    private Context context;

    /**
     * 线程的数量
     */
    private  int threadCount = 1;
    /**
     * 每个下载区块的大小
     */
    private  long blocksize;
    /**
     * 正在运行的线程的数量
     */
    private  int runningThreadCount;


    public MutileThreadDownload(Context context){
        this.context = context;
    }

    /**
     *
     * @param downUrl
     * @throws Exception
     */
    public  void startDown( String downUrl, String name,  String packname,
                            String pic, String webUrl, String type) {

        if(TextUtils.isEmpty(downUrl)){
            return;
        }

        String downUrl_old = AppConfigManager.getInstance().readConfig("main_down_game_url", "");
        if(!TextUtils.isEmpty(downUrl_old)){
            //如果之前有没有下载完成的则 此次下载之前的
            downUrl = downUrl_old;
            name = AppConfigManager.getInstance().readConfig("main_down_game_name","");
            packname = AppConfigManager.getInstance().readConfig("main_down_game_packname","");
            pic = AppConfigManager.getInstance().readConfig("main_down_game_pic","");
            webUrl = AppConfigManager.getInstance().readConfig("main_down_game_webUrl","");
            type = AppConfigManager.getInstance().readConfig("main_down_game_type","");
        }
        //  1  表示不再下载，服务端配置这个 代表，客户端只把之前未下载的下载 不再下载新的
        if(!TextUtils.equals("1",downUrl)){
            //开始下载逻辑
            download(downUrl,name,packname,pic,webUrl,type);
        }

    }


    /**
     * 下载
     * @param downUrl
     * @param name
     * @param packname
     * @param pic
     * @param webUrl
     */
    public void download(final String downUrl,final String name, final String packname,
                          final String pic,final String webUrl,final String type ) {
        new Thread(){
            @Override
            public void run() {
                try {
                    String apkName ;
                    if(!TextUtils.isEmpty(packname)){
                        apkName = packname;
                    }else if(!TextUtils.isEmpty(name)){
                        apkName = name;
                    }else{
                        apkName = StringUtils.md5(downUrl);
                    }
                    String target = AppConfigTools.APKFLODER + AppConfigTools.SPREARATOR + apkName + ".apk";
                    if(TextUtils.isEmpty(target)){
                        return;
                    }
                    if(!isDownload(target,packname,pic,webUrl,type)){
                        //如果已经下载了安装包则不再下载
                        return;
                    }
                    StatService.onEvent(context, "069", "游戏请求下载", 1);// 统计的点击资讯的次数
                    //服务器路径
                    URL url = new URL(downUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(5000);
                    int code = conn.getResponseCode();
                    if(code == 200) {
                        long size = conn.getContentLength();//得到服务器端返回的文件的大小

                        blocksize = size / threadCount;
                        //1.首先在本地创建一个大小跟服务器一模一样的空白文件
                        File file = new File(target);
                        if(!file.getParentFile().exists()){
                         file.getParentFile().mkdirs();
                        }
                        RandomAccessFile raf = new RandomAccessFile(file, "rw");
                        raf.setLength(size);
                        //2.开启若干个子线程分别去下载对应的资源
                        runningThreadCount = threadCount;
                        //开始下载 则记录本次的下载信息
                        SharedPreferences sharedPreferences = AppConfigManager.getInstance().getConfigSP();
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("main_down_game_url", downUrl);
                        editor.putString("main_down_game_name", name);
                        editor.putString("main_down_game_packname", packname);
                        editor.putString("main_down_game_pic", pic);
                        editor.putString("main_down_game_webUrl", webUrl);
                        editor.putString("main_down_game_type", type);
                        editor.putString(packname,packname);//记录这个文件处于下载状态
                        editor.commit();
                        for(int i = 1;i <= threadCount; i++) {
                            long startIndex = (i - 1) * blocksize;
                            long endIndex = i * blocksize - 1;
                            if(i == threadCount) {
                                //最后一个线程
                                endIndex = size - 1;
                            }
                          DownloadThread downloadThread =   new DownloadThread(i, startIndex, endIndex, downUrl, target,packname,pic,webUrl,type);
                            if(downloadThreads == null){
                                downloadThreads = new ArrayList<DownloadThread>();
                            }
                            downloadThreads.add(downloadThread);
                            downloadThread.start();
                        }

                    }
                    conn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 获取文件已经下载的长度
     * @param target
     * @return
     */
    private boolean isDownload(String target,String packname,String pic,String webUrl,String type){
        File file = new File(target);
        String downStau = AppConfigManager.getInstance().readConfig(packname,"");
        boolean isinsall = AppTools.isAppInstall(AppApplication.getInstance(), packname);
        if(isinsall){
            //如果安装了 就不再下载
            return false;
        }
       if(file.exists() && TextUtils.isEmpty(downStau)){
            //文件存在并且下载完成
           if(TextUtils.equals(type, AdConfig.AD_VIEW_TYPE_LIST_NATIVE_DIALOG_WEB)){
               //如果是网页则直接展示
               showWebDialog(webUrl, target,packname);
           }else{
               //弹出安装apk窗体的逻辑
               showGameInsallDialog(pic,target,packname);
           }

            return false;
        }
        if(NetUtils.getNetworkType() == NetUtils.NETTYPE_WIFI){
            return true;
        }
        return false;
    }


    /**
     * 判断当前时间是否允许展示
     * @return
     */
    private boolean isTime(){
        long oldShowTime = AppConfigManager.getInstance().readConfig("main_game_dialog_time", 0L);
        String jiange = AppConfigManager.getInstance().readConfig("main_game_interval_time", "12");
        int jiangetime = StringUtils.toInt(jiange,12);
        if(jiangetime == -1){
            //关闭弹窗
            return  false;
        }else if(jiangetime == 0){
            //去除时间限制,每次都弹
            return true;
        }
        final long oneDayMS = jiangetime * 60 * 60 * 1000;//个小时的毫秒数
        long currentTime = System.currentTimeMillis();// 当前时间

        long chazhi_millis = currentTime - oldShowTime;// 相差的毫秒数
        final int days = (int) (chazhi_millis / oneDayMS);
        if(days >= 1){
            //说明过了限定的小时
            return true;
        }
        return false;
    }

    /**
     * 展示游戏安装弹窗
     * @param thumbUrl
     */
    private void showGameInsallDialog(final String thumbUrl, final String file, final String packname){
        if(!isTime()){
            //没有通过时间条件 则不展示弹窗
            return;
        }
        final View activityDialog = LayoutInflater.from(context).inflate(R.layout.dialog_activity, null);
        final CustomImageView thumb = (CustomImageView) activityDialog.findViewById(R.id.thumb);
        thumb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StatService.onEvent(context, "069", "游戏图片点击", 1);// 统计的点击资讯的次数
                boolean  b =  AppUtils.isinstall(context, packname);
                if(b){
                    //如果安装了则直接打开
                    AppUtils.startUpApp(context,packname);
                }else{
                    //点击安装app
                    File appFile= new File(file);
                    com.app.okhttplib.util.AppUtils.installAPP(context,appFile);
                }
            }
        });
        LoadImageUtils.getInstance().downloadImage(thumbUrl, new LoadImageUtils.OnImageDownloadedListener() {
            @Override
            public void loadImage() {
                if(context == null || ((Activity)context).isFinishing()){
                    return;
                }
                ((Activity)context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
//                            LoadImageUtils.getInstance().loadImage(thumb, thumbUrl, new AutoHeightControllerListener<ImageInfo>(thumb, 560));
                            LoadImageUtils.getInstance().loadImageGif(thumb, thumbUrl, new AutoHeightControllerListener<ImageInfo>(thumb, 560));
                            final Dialog dialog = new DismisiDialog(context, R.style.CustomDialogStyle);
                            View cancle = activityDialog.findViewById(R.id.iv_cancle);
                            cancle.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (dialog != null) {
                                        dialog.cancel();
                                    }
                                }
                            });
                            dialog.setCanceledOnTouchOutside(false);
//                        dialog.setOnKeyListener(dialogListener);
                            dialog.requestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
                            dialog.show();
                            if (dialog.getWindow() != null) {
                                dialog.getWindow().getAttributes().gravity = Gravity.CENTER;
                                WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                                attributes.width = ViewSizeUtils.dp2px(context, 310);
                                dialog.getWindow().setAttributes(attributes);
                                dialog.setCancelable(true);
                            }
                            dialog.setContentView(activityDialog);
                            //记录本次展示弹窗的时间
                            AppConfigManager.getInstance().writeConfig("main_game_dialog_time", System.currentTimeMillis());
                            StatService.onEvent(context, "069", "游戏图片弹窗", 1);// 统计的点击资讯的次数
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void fail(String error) {
            }
        });
    }

    /**
     * 展示网页弹窗
     * @param weburl
     */
    private void showWebDialog(final String weburl, final String tareget, final String packname){
        if(!isTime()){
            //没有通过时间条件 则不展示弹窗
            return;
        }

        ((Activity)context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                final View activityDialog = LayoutInflater.from(context).inflate(R.layout.dialog_web, null);
                FrameLayout frameLayout = (FrameLayout) activityDialog.findViewById(R.id.web_fram);


                final CustomWebView webView = new CustomWebView(context);
                frameLayout.addView(webView);
                WebSettings settings = webView.getSettings();
//        settings.setBlockNetworkImage(true);// 延迟图片加载
                settings.setJavaScriptCanOpenWindowsAutomatically(true);
                //手动获取焦点
                webView.setFocusable(true);
                webView.setWebViewClient(new WebViewClient());

                webView.requestFocus();
                webView.loadUrl(weburl);
                try {
                    webView.addJavascriptInterface(new JavascriptInterface(context, tareget, packname), "app_js");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT >= 19) {
                    settings.setLoadsImagesAutomatically(true);
                } else {
                    settings.setLoadsImagesAutomatically(false);
                }
                try {
                    final Dialog dialog = new DismisiDialog(context, R.style.CustomDialogStyle);
                    View cancle = activityDialog.findViewById(R.id.iv_cancle);
                    cancle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (dialog != null) {
                                webView.destroy();
                                dialog.cancel();
                            }
                        }
                    });
                    dialog.setCanceledOnTouchOutside(false);
                    dialog.requestWindowFeature(Window.FEATURE_ACTION_MODE_OVERLAY);
                    dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                                webView.destroy();
                                dialog.cancel();
                            }
                            return true;
                        }
                    });
                    dialog.show();
                    if (dialog.getWindow() != null) {
                        dialog.getWindow().getAttributes().gravity = Gravity.CENTER;
                        WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
                        attributes.width = ViewSizeUtils.dp2px(context, 310);
                        dialog.getWindow().setAttributes(attributes);
                        dialog.setCancelable(true);
                    }
                    dialog.setContentView(activityDialog);
                    //记录本次展示弹窗的时间
                    AppConfigManager.getInstance().writeConfig("main_game_dialog_time", System.currentTimeMillis());

                    StatService.onEvent(context, "069", "游戏网页弹窗", 1);// 统计的点击资讯的次数
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });


    }

    // js通信接口
    public class JavascriptInterface {


        private Context context;
        private String target;
        private String packname;

        public JavascriptInterface(Context context,String target,String packname) {
            this.context = context;
            this.target = target;
            this.packname = packname;
        }

        @android.webkit.JavascriptInterface
        public void insallApp() {

            StatService.onEvent(context, "069", "游戏网页点击", 1);// 统计的点击资讯的次数
            boolean  b =  AppUtils.isinstall(context, packname);
            if(b){
                //如果安装了则直接打开
                AppUtils.startUpApp(context,packname);
            }else{
                //点击安装app
                File appFile= new File(target);
                com.app.okhttplib.util.AppUtils.installAPP(context, appFile);
            }
        }

    }


    /**
     * 关闭线程
     */
    public static void closeDownList(){
        if(downloadThreads != null){
            for(int i=0;i<downloadThreads.size();i++){
                DownloadThread downloadThread = downloadThreads.get(i);

                if(downloadThread != null){
                    try {
                        downloadThread.stop();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public  class DownloadThread extends Thread {
        private int threadId;
        private long startIndex;
        private long endIndex;
        private String path;
        private String target;
        private String packname;
        private String pic;
        private String weburl;
        private String type;

        public DownloadThread(int threadId, long startIndex, long endIndex,
                              String path,String target,String packname,String pic,String weburl,String type) {
            super();
            this.threadId = threadId;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
            this.path = path;
            this.target = target;
            this.packname = packname;
            this.pic = pic;
            this.weburl = weburl;
            this.type = type;
        }

        public void run() {
            boolean isExcept = false;
            FileInputStream fis = null;
            InputStream is = null;
            RandomAccessFile raf = null;
            try {
                //当前线程下载的总大小
                int total = 0;
                File positionFile = new File(AppConfigTools.APKFLODER + AppConfigTools.SPREARATOR +threadId +packname+ ".txt");
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                //接着从上一次的位置继续下载数据
                if(positionFile.exists() && positionFile.length() > 0) {  //判断是否有记录
                    fis = new FileInputStream(positionFile);
                    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                    //获取当前线程上次下载的总大小是多少次下载的总大小
//                    fis.close();
                    String lasttotalstr = br.readLine();
                    int lastTotal = Integer.valueOf(lasttotalstr);
                    startIndex += lastTotal;  //加上上
                }

                conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
                conn.setConnectTimeout(5000);
                int code = conn.getResponseCode();
                is = conn.getInputStream();
                File file = new File(target);
                raf = new RandomAccessFile(file, "rw");
                raf.seek(startIndex);

                int len = 0;
                byte[] buffer = new byte[1024 * 1024];
                while((len = is.read(buffer)) != -1) {
                    RandomAccessFile rf = new RandomAccessFile(positionFile, "rwd");//"rwd"   打开以便读取和写入，对于 "rw"，还要求对文件内容的每个更新都同步写入到底层存储设备。  
                    raf.write(buffer, 0, len);
                    total += len;
                    rf.write(String.valueOf(total).getBytes());
                    rf.close();
                }
//                is.close();
//                raf.close();
                //conn.disconnect();

            } catch (Exception e) {
                e.printStackTrace();
                isExcept = true;
                new Thread() {
                    public void run() {
                        AppFileUtils.clearCache(new File(AppConfigTools.APKFLODER));// 清除apk
                    }

                }.start();
            }finally {
                try {
                    if(fis != null){
                        fis.close();
                    }
                    if(is != null){
                        is.close();
                    }
                    if(raf != null){
                        raf.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(isExcept){
                    return;
                }
                //只有所有线程都下载完毕后，才可以删除记录文件
                synchronized (MutileThreadDownload.class) {   //线程安全
                    runningThreadCount--;
                    if(runningThreadCount < 1) {
                        try {
                            for (int i = 1; i <= threadCount; i++) {
                                File f = new File(AppConfigTools.APKFLODER + AppConfigTools.SPREARATOR +i +packname+ ".txt");
                                boolean  b = f.delete();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //下载完成后展示游戏弹窗
                        if(TextUtils.equals(type, AdConfig.AD_VIEW_TYPE_LIST_NATIVE_DIALOG_WEB)){
                            //如果是网页则直接展示
                            showWebDialog(weburl,target,packname);
                        }else {
                            showGameInsallDialog(pic,target,packname);
                        }
                        //下载完成则清除本地存储的下载信息
                        SharedPreferences sharedPreferences = AppConfigManager.getInstance().getConfigSP();
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("main_down_game_url", "");
                        editor.putString("main_down_game_name", "");
                        editor.putString("main_down_game_packname", "");
                        editor.putString("main_down_game_pic", "");
                        editor.putString("main_down_game_webUrl", "");
                        editor.remove(packname);//移除的当前文件的下载状态
                        editor.apply();
                        StatService.onEvent(context, "069", "游戏下载成功", 1);// 统计的点击资讯的次数
                    }
                }
            }
        }
    }
}